package pers.youqu.page.canal;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pers.youqu.page.service.GoodsPageService;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.context.CanalContext;
import top.javatool.canal.client.handler.EntryHandler;

import java.util.Map;

/**
 * @author Jason
 * @version 1.0.0
 * @date 2020/12/17 9:54
 * @Description 相当于Canal的监听器，当检测到表数据发生变化时操作对应中的redis缓存
 *  【删除表数据：删除redis缓存，增加/修改表数据：redis重新获取缓存】
 */
@Slf4j
@CanalTable(value = "all")
@Component
public class CanalHandler implements EntryHandler<Map<String, String>> {
    @Autowired
    private GoodsPageService goodsPageService;

    @Override
    public void insert(Map<String,String> model) {
        // 获取表的名称
        String table = CanalContext.getModel().getTable();
        // 如果表是tb_sku
        if("tb_sku".equals(table)){
            log.info("sku新增了{}", model);
            // 新增重新拉取缓存
            goodsPageService.loadSkuListData(Long.valueOf(model.get("spu_id")));
        }
    }

    @Override
    public void update(Map<String,String> before, Map<String,String> after) {
        String table = CanalContext.getModel().getTable();
        if("tb_sku".equals(table)){
            log.info("sku修改了{}", after);
            // 修改从新拉取
            goodsPageService.loadSkuListData(Long.valueOf(after.get("spu_id")));
        }
    }

    @Override
    public void delete(Map<String,String> model) {
        String table = CanalContext.getModel().getTable();
        if("tb_sku".equals(table)){
            log.info("sku删除了{}", model);
            // sku删除后从redis缓存中也删除
            goodsPageService.deleteSku(Long.valueOf(model.get("spu_id")));
        }
    }
}
